<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>智能E生</title>
  <link rel="stylesheet" href="../css/asking.css">
  <link rel="stylesheet" href="../vandor/font-awesome/css/all.min.css">
</head>
<body>
<!-- 顶部导航栏 -->
<div class="chat-header">
  <a href="javascript:history.back()" class="back-button">
    <i class="fas fa-arrow-left"></i>
  </a>
  <div class="chat-info">
    <img src="../image/docter.jpg" alt="助手头像" class="chat-avatar">
    <div>
      <div class="chat-title">智能问诊助手</div>
      <div class="chat-status">在线</div>
    </div>
  </div>
<!--  <div class="chat-actions">
    <a href="#" class="chat-action">
      <i class="fas fa-ellipsis-v"></i>
    </a>
  </div>-->
</div>

<!-- 消息列表 -->
<div class="messages-container" id="messagesContainer">
  <!-- 系统欢迎消息 -->
  <div class="message-row received">

  </div>
</div>
<script src="../js/common.js"></script>
<script>
  // 用户头像
  const userAvatar = "../image/customer.jpg";

  // DOM元素
  const messagesContainer = document.getElementById('messagesContainer');
  let currentQuestionIndex = 0;
  let currentQuestionId = null;
  let selectedMultiOptions = [];
  let tipList = ["大模型","模式","性别","最近一次月经时间","年龄","主诉","药物过敏史",];
  let msgList = [];
  let simpleList = [];
  let askList = [];
  let sex = ""
  let usedQ = [];
  let currQ = [];
  let zhushu = "";
  let flag = false;
  let mode = "";
  let storage = window.localStorage;
  let usercode = "";
  let username = "";
  let medicalrecordcode = "";
  let modelMode = "Deepseek Chat";

  //1.初始化
  init();
  function init(){

    var userModel = storage.getItem("userModel");
    if(userModel){
      var userData = JSON.parse(userModel);
      if(userData){
        usercode = userData.usercode;
        username = userData.username;
      }else{
        alert("请登录系统")
        window.location.href = "login.html";
        return;
      }
    }else{
      alert("请登录系统")
      window.location.href = "login.html";
      return;
    }

    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const typingIndicator = document.createElement('div');
    typingIndicator.className = 'message-row received';
    typingIndicator.innerHTML = `
                <div class="message-container">
                    <img src="../image/docter.jpg" alt="助手头像" class="message-avatar">
                    <div class="message-content-area">
                        <div class="message-content">
                            <p>您好！我是智能问答助手 🤖</p>
                            <p>我将询问您几个问题，请根据问题类型选择适当的回答方式。</p>
                        </div>
                        <div class="message-meta">
                            <span class="message-time">${hours}:${minutes}</span>
                        </div>
                    </div>
                </div>
            `;
    messagesContainer.appendChild(typingIndicator);
    scrollToBottom();
  }

  //2.先问基础问题
  var questions = [
    {
      id: 1,
      type: "options",
      question: "请您选择问诊时使用的大模型？",
      tips:"大模型",
      answer: "",
      hint: "请选择问诊时使用的大模型",
      options: ["Deepseek Chat","Deepseek R1","Kimi 8","Kimi 32","Kimi 128"],
      totalQuestions: 7
    },
    {
      id: 2,
      type: "options",
      question: "请您选择问诊时使用的模式？",
      tips:"模式",
      answer: "",
      hint: "快速诊断模式，适合提供常见病和多发病的诊断及建议。<br>精确诊断模式，适用于疑难病及罕见病的诊断，因为鉴别诊断对比的需要，可能存在提问较多，持续时间稍长，反复提问可能，请您耐心回答，这样将给到您更加精准的诊断建议，谢谢您的配合。",
      options: ["快速模式","精准模式"],
      totalQuestions: 7
    },
    {
      id: 3,
      type: "options",
      question: "请选择您的性别？",
      tips:"性别",
      answer: "",
      hint: "请从以下选项中选择",
      options: ["男性", "女性"],
      totalQuestions: 7
    },
    {
      id: 4,
      type: "date",
      question: "请选择您最近一次月经时间",
      tips:"最近一次月经时间",
      answer: "",
      hint: "请选择日期",
      totalQuestions: 7
    },
    {
      id: 5,
      type: "date",
      question: "请选择您的出生日期",
      tips:"年龄",
      answer: "",
      hint: "请选择日期",
      totalQuestions: 7
    },
    {
      id: 6,
      type: "text",
      question: "请您输入当前最不舒服的症状和持续时间？",
      tips:"主诉",
      answer: "",
      hint: "请您输入当前最不舒服的症状和持续时间？如左手痛，持续时间一周......",
      totalQuestions: 7
    },
    {
      id: 7,
      type: "text",
      question: "请您输入过敏的药物？",
      tips:"药物过敏史",
      answer: "",
      hint: "请您输入过敏的药物？如西力欣",
      totalQuestions: 7
    }/*,
                {
                    id: 4,
                    type: "multi-options",
                    question: "您喜欢哪些运动？（可多选）",
                    answer: ["篮球", "游泳"],
                    hint: "请选择所有适用的选项",
                    options: ["跑步", "游泳", "篮球", "足球", "羽毛球"],
                    totalQuestions: 5
                }*/
  ];

  getQuestionForBase();
  function getQuestionForBase() {
    // 显示"正在输入"指示器
    const typingIndicator = document.createElement('div');
    typingIndicator.className = 'message-row received';
    typingIndicator.innerHTML = `
                <div class="message-container">
                    <img src="../image/docter.jpg" alt="助手头像" class="message-avatar">
                    <div class="typing-text">助手正在输入...</div>
                    <div class="typing-indicator">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                </div>
            `;
    messagesContainer.appendChild(typingIndicator);
    scrollToBottom();

    // 模拟AJAX请求获取问题
    setTimeout(() => {
      if(flag){
        flag = false;
        questions = [];
        console.log("生成病历")
        msgList.push({"role":"user","content":"生成病历"})
        fetch("/AiMedical/api/deepseek/addRecordDS",{
          method: "POST",
          headers:{
            "Content-Type":"application/json"
          },
          body:JSON.stringify({
            "model":"deepseek-chat",
            "messages":msgList,
            "stream":false,
            "stopFlag":true
          }),
        }).then(
          response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.text();
          }
        ).then(data => {
          // 移除"正在输入"指示器
          messagesContainer.removeChild(typingIndicator);

          questions = [{
            id: 1,
            type: "options",
            question: '根据您以上的描述，生成如下病历。',
            tips:"病历",
            answer: "",
            hint: data.replaceAll("\n","<br>"),
            options: ["再试一次"],
            totalQuestions: 1
          }];

          //保存病历
          if(medicalrecordcode){
            fetch("/AiMedical/api/medicalrecord/edit",{
              method: "POST",
              headers:{
                "Content-Type":"application/json"
              },
              body:JSON.stringify({
                code:medicalrecordcode,
                usercode : usercode,
                username : username,
                zhushu : zhushu,
                medicalrecord:JSON.stringify(msgList),
                askrecord:JSON.stringify(askList)
              }),
            }).then(
                    response => response.json()
            ).then(data => {
              console.log('保存过程成功');
            }).catch(error => {
              console.error('保存过程失败:', error);

            });
          }


          //重新开始计数
          currentQuestionIndex = 0;
          getQuestionForBase();

        }).catch(error => {
          console.error('生成病历失败:', error);
          showError('生成病历失败，请重试');
        });
        return;

      }else{
        if (currentQuestionIndex >= questions.length && flag == '') {
          //问完之后，开始ds查询
          questions = [];
          var senddata = [];
          if(mode == "精准模式"){
            senddata = simpleList;
          }else{
            senddata = msgList;
          }
          fetch("/AiMedical/api/deepseek/askDs",{
            method: "POST",
            headers:{
              "Content-Type":"application/json"
            },
            body:JSON.stringify({
              //"model":"deepseek-chat",
              "model": modelMode,
              "messages": senddata,
              "stream":false,
              "stopFlag":false
            }),
          }).then(
                  response => response.json()
          ).then(data => {

            // 移除"正在输入"指示器
            messagesContainer.removeChild(typingIndicator);

            //如果是返回数组，那就是问题
            if(Array.isArray(data)){
              currQ = data;
              var allIncludes = false;
              //只要有没问过的，就继续提问
              for(x=0;x<currQ.length;x++){
                if(!usedQ.includes(currQ[x].keywords)){
                  allIncludes = true;
                  break;
                }
              }
              if(!allIncludes){
                //结束
                showCompletionMessage();
              }else{
                //处理问题
                var length1 = data.length;
                data.forEach((item,index) => {
                  questions.push({
                    id: index,
                    type: "multi-options",
                    question: item.question,
                    tips:item.keywords,
                    answer: "",
                    hint: "请选择所有适用的选项",
                    options: JSON.parse(item.answer),
                    totalQuestions: length1
                  })
                });
                //重新开始计数
                currentQuestionIndex = 0;
                getQuestionForBase();
              }
              return;
            }else{//不是数组，就是答案

              var json1 = data;
              //诊断的检查
              var diagnostic_check = json1.diagnosticCheck;
              var obj1 = {
                "role" : "user",
                "content": "辅助检查："+ diagnostic_check + ";"
              }
              msgList.push(obj1);
              //化验项目
              var laboratory_item = json1.laboratoryItem;
              obj1 = {
                "role" : "user",
                "content": "化验项目："+ laboratory_item + ";"
              }
              msgList.push(obj1);
              //临时服用的药物
              var medical = json1.medical;
              obj1 = {
                "role" : "user",
                "content": "临时用药："+ medical + ";"
              }
              msgList.push(obj1);
              //诊疗方案
              var diagnostic = json1.diagnostic;
              obj1 = {
                "role" : "user",
                "content": "初步诊断："+ diagnostic + ";"
              }
              msgList.push(obj1);
              //注意事项
              var tips = json1.tips;
              obj1 = {
                "role" : "user",
                "content": "注意事项："+ tips + ";"
              }
              msgList.push(obj1);

              var html =
                      '<span class="result-span-title">初步诊疗 : </span><br><span class="result-span-text">'+diagnostic+'</span>' + '<br>' +
                      '<span class="result-span-title">辅助检查:</span><br><span class="result-span-text"> '+diagnostic_check+'</span>'+ '<br>' +
                      '<span class="result-span-title">化验项目 : </span><br><span class="result-span-text">'+laboratory_item+'</span>' + '<br>' +
                      '<span class="result-span-title">临时用药 : </span><br><span class="result-span-text">'+medical+'</span>' + '<br>' +
                      '<span class="result-span-title">注意事项 : </span><br><span class="result-span-text">'+tips+'</span>' + '<br>' ;
              questions = [{
                id: 1,
                type: "options",
                question: '根据您的主诉（'+ zhushu +'），以及上面问题的问答，得出以下的诊断',
                tips:"诊断",
                answer: "",
                hint: html,
                options: ["生成病历"],
                totalQuestions: 1
              }];

              askList = msgList;
              //保存问诊过程
              fetch("/AiMedical/api/medicalrecord/add",{
                method: "POST",
                headers:{
                  "Content-Type":"application/json"
                },
                body:JSON.stringify({
                  usercode : usercode,
                  username : username,
                  zhushu : zhushu,
                  askrecord:JSON.stringify(askList)
                }),
              }).then(
                      response => response.json()
              ).then(data => {
                console.log('保存过程成功');
              }).catch(error => {
                console.error('保存过程失败:', error);

              });


              //重新开始计数
              currentQuestionIndex = 0;
              getQuestionForBase();
            }

          }).catch(error => {
            console.error('查询失败:', error);
            showError('查询失败，请重试');
          });
          return;
        }
      }

      questionData = questions[currentQuestionIndex];
      //要是男性，而且当前问题是“最近一次月经时间”，不需要问下一个月经史的问题
      if(sex == "男性" && questionData.tips == "最近一次月经时间"){
        currentQuestionIndex ++;
        //然后重新取值
        questionData = questions[currentQuestionIndex];
      }

      currentQuestionId = questionData.id;
      //收集提问过的关键词
      usedQ.push(questionData.tips)
      selectedMultiOptions = []; // 重置多选选项

      // 移除"正在输入"指示器
      messagesContainer.removeChild(typingIndicator);

      // 显示问题
      showQuestion(questionData);

    }, 1500);
  }

  // 显示问题
  function showQuestion(questionData) {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');

    const currday = getSmpFormatDate(now,false);
    console.log(currday)

    const questionMessage = document.createElement('div');
    questionMessage.className = 'message-row received';

    // 根据问题类型生成不同的输入方式
    let inputField = '';
    if (questionData.type === "text") {
      inputField = `
                    <div class="question-input-container">
                        <input type="text" class="question-input-field" placeholder="输入答案...">
                        <button class="question-send-button">
                            <i class="fas fa-paper-plane"></i> 提交
                        </button>
                    </div>
                `;
    } else if (questionData.type === "date") {

      inputField = `
                    <div class="question-input-container">
                        <input type="date" class="question-date-field" max="${currday}">
                        <button class="question-send-button">
                            <i class="fas fa-paper-plane"></i> 提交
                        </button>
                    </div>
                `;
    } else if (questionData.type === "options") {
      inputField = `
                    <div class="options-container">
                        ${questionData.options.map(option =>
              `<div class="option-button" data-answer="${option}">${option}</div>`
      ).join('')}
                    </div>
                `;
    } else if (questionData.type === "multi-options") {
      inputField = `
                    <div class="options-container">
                        ${questionData.options.map(option =>
              `<div class="multi-option-button" data-answer="${option}">${option}</div><br>`
      ).join('')}
                    </div>
                    <input style="margin-top: 10px;width: 100%" type="text" class="question-input-field" placeholder="输入其他答案...">
                    <button class="multi-submit-button">
                        <i class="fas fa-paper-plane"></i> 提交选择
                    </button>
                `;
    }

    questionMessage.innerHTML = `
                <div class="message-container">
                    <img src="../image/docter.jpg" alt="助手头像" class="message-avatar">
                    <div class="message-content-area">
                        <div class="message-content">
                            <p>${questionData.question}</p>
                            <div class="question-hint">${questionData.hint}</div>
                            ${inputField}
                        </div>
                        <div class="message-meta">
                            <span class="message-time">${hours}:${minutes}</span>
                        </div>
                    </div>
                </div>
            `;

    messagesContainer.appendChild(questionMessage);
    scrollToBottom();

    // 添加事件监听器
    if (questionData.type === "text" || questionData.type === "date") {
      const inputField = questionMessage.querySelector(questionData.type === "text" ? '.question-input-field' : '.question-date-field');
      const sendButton = questionMessage.querySelector('.question-send-button');

      // 聚焦输入框
      //inputField.focus();

      // 点击发送按钮
      sendButton.addEventListener('click', function() {
        const answer = inputField.value.trim();
        if (answer) {
          sendAnswerToServer(currentQuestionId, answer);
        }
      });

      // 按Enter键(仅文本输入)
      if (questionData.type === "text") {
        inputField.addEventListener('keypress', function(e) {
          if (e.key === 'Enter') {
            const answer = inputField.value.trim();
            if (answer) {
              sendAnswerToServer(currentQuestionId, answer);
            }
          }
        });
      }
    } else if (questionData.type === "options") {
      const optionButtons = questionMessage.querySelectorAll('.option-button');
      optionButtons.forEach(button => {
        button.addEventListener('click', function() {
          if(questionData.tips=="病历"){
            location.reload();
            return;
          }
          const answer = this.getAttribute('data-answer');
          sendAnswerToServer(currentQuestionId, answer);
        });
      });
    } else if (questionData.type === "multi-options") {
      const optionButtons = questionMessage.querySelectorAll('.multi-option-button');
      const submitButton = questionMessage.querySelector('.multi-submit-button');

      //
      const inputField = questionMessage.querySelector('.question-input-field');
      // 聚焦输入框
      //inputField.focus();


      optionButtons.forEach(button => {
        button.addEventListener('click', function() {
          const answer = this.getAttribute('data-answer');
          const index = selectedMultiOptions.indexOf(answer);

          if (index === -1) {
            // 未选中，添加到选中列表
            selectedMultiOptions.push(answer);
            this.classList.add('selected');
          } else {
            // 已选中，从选中列表移除
            selectedMultiOptions.splice(index, 1);
            this.classList.remove('selected');
          }
        });
      });

      submitButton.addEventListener('click', function() {
        const answer1 = inputField.value.trim();
        if(answer1){
          selectedMultiOptions.push(answer1)
        }
        if (selectedMultiOptions.length > 0 || answer1) {
          sendAnswerToServer(currentQuestionId, selectedMultiOptions);
        }
      });
    }
  }

  // 发送答案到服务器
  function sendAnswerToServer(questionId, answer) {
    // 显示用户回答
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');

    const userMessage = document.createElement('div');
    userMessage.className = 'message-row sent';

    // 处理数组类型的答案（多选题）
    const answerText = Array.isArray(answer) ? answer.join('、') : answer;

    userMessage.innerHTML = `
                <div class="message-container">
                    <img src="${userAvatar}" alt="用户头像" class="message-avatar">
                    <div class="message-content-area">
                        <div class="message-content">${answerText}</div>
                        <div class="message-meta">
                            <span class="message-time">${hours}:${minutes}</span>
                        </div>
                    </div>
                </div>
            `;
    messagesContainer.appendChild(userMessage);
    scrollToBottom();

    // 模拟AJAX请求提交答案
    setTimeout(() => {
      /*// 模拟正确答案数据
      const correctAnswers = {
          1: "张三",
          2: "苹果",
          3: "1990-01-01",
          4: ["篮球", "游泳"],
          5: "蓝色"
      };

      let isCorrect;

      if (Array.isArray(correctAnswers[questionId])) {
          // 多选题比较
          const correctArray = correctAnswers[questionId];
          const answerArray = Array.isArray(answer) ? answer : [answer];

          // 检查两个数组是否包含相同的元素（顺序不重要）
          isCorrect = correctArray.length === answerArray.length &&
              correctArray.every(item => answerArray.includes(item));
      } else {
          // 单选题比较
          isCorrect = answer === correctAnswers[questionId];
      }

      const correctAnswerText = Array.isArray(correctAnswers[questionId]) ?
          correctAnswers[questionId].join('、') : correctAnswers[questionId];*/
      //收集答案
      const questionData = questions[currentQuestionIndex];

      if(questionData.tips!="诊断"){
        if(tipList.indexOf(questionData.tips) != -1){
          if(questionData.tips=="性别"){
            sex = answer;
          }
          if(questionData.tips=="主诉"){
            zhushu = answer;
          }

          if(questionData.tips=="大模型"){
/*            if(answer == "Kimi 128"){
              modelMode = "moonshot-v1-128k"
            }else{
              modelMode = "deepseek-chat";
            }*/
            modelMode = answer;
          }

          if(questionData.tips!="模式"){
            if(questionData.tips=="年龄"){
              var age = getAges(answer)
              simpleList.push({
                "role":"user",
                "content":questionData.tips +"："+age
              })
              msgList.push({
                "role":"user",
                "content":questionData.tips +"："+age
              })
            }else{
              if(questionData.tips!="大模型"){
                simpleList.push({
                  "role":"user",
                  "content":questionData.tips +"："+answer
                })
                msgList.push({
                  "role":"user",
                  "content":questionData.tips +"："+answer
                })
              }

            }

          }else{
            //赋值选择的模式
            mode = answer;
          }
        }else{
          simpleList.push({
            "role":"user",
            "content": answer +""
          });
          msgList.push({
            "role":"user",
            "content":"问题："+ questionData.question +",答案："+answer
          })
        }
      }else {
        flag = true;
      }

      showFeedback(answerText);
      currentQuestionIndex++;
      getQuestionForBase();
    }, 1000);
  }

  // 显示反馈
  function showFeedback(answerText) {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');

    const feedbackMessage = document.createElement('div');
    feedbackMessage.className = 'message-row received';

    feedbackMessage.innerHTML = `
                <div class="message-container">
                    <img src="../image/docter.jpg" alt="助手头像" class="message-avatar">
                    <div class="message-content-area">
                        <div class="message-content feedback-correct">
                            <i class="fas fa-check-circle"></i> 您的回答是：<br>
                            <small>${answerText}</small>
                        </div>
                        <div class="message-meta">
                            <span class="message-time">${hours}:${minutes}</span>
                        </div>
                    </div>
                </div>
            `;

    messagesContainer.appendChild(feedbackMessage);
    scrollToBottom();
  }

  // 显示完成消息
  function showCompletionMessage() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');

    const completionMessage = document.createElement('div');
    completionMessage.className = 'message-row received';
    completionMessage.innerHTML = `
                <div class="message-container">
                    <img src="../image/docter.jpg" alt="助手头像" class="message-avatar">
                    <div class="message-content-area">
                        <div class="completion-message">
                            <h3><i class="fas fa-trophy"></i> 问答完成！</h3>
                            <p>您已经回答了所有问题，感谢您的参与！</p>
                        </div>
                        <div class="message-meta">
                            <span class="message-time">${hours}:${minutes}</span>
                        </div>
                    </div>
                </div>
            `;

    messagesContainer.appendChild(completionMessage);
    scrollToBottom();
  }

  // 显示错误消息
  function showError(message) {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');

    const errorMessage = document.createElement('div');
    errorMessage.className = 'message-row received';
    errorMessage.innerHTML = `
                <div class="message-container">
                    <img src="../image/docter.jpg" alt="助手头像" class="message-avatar">
                    <div class="message-content-area">
                        <div class="message-content feedback-incorrect">
                            <i class="fas fa-exclamation-circle"></i> ${message}
                        </div>
                        <div class="message-meta">
                            <span class="message-time">${hours}:${minutes}</span>
                        </div>
                    </div>
                </div>
            `;

    messagesContainer.appendChild(errorMessage);
    scrollToBottom();
  }

  // 滚动到底部
  function scrollToBottom() {
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }
</script>
</body>
</html>